package accountManagement.servlet;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import accountManagement.Account;
import accountManagement.Admin;
import accountManagement.AccountManager;

/**
 * Servlet implementation class ServletVisualizzaListaAccount
 */
@WebServlet("/ServletSearchAccount")
public class ServletSearchAccount extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletSearchAccount() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

    private void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	try {
    		Object user = request.getSession().getAttribute("user");
        	if(user == null || !(user instanceof Admin)) {
        		throw new InvalidParameterException("Non disponi dei privilegi necessari per accedere alla pagina richiesta");
        	} 
    		// Parametri della ricerca
    		String nickname = request.getParameter("nickname");
    		
    		// Creazione del contenuto della risposta
    		AccountManager manager = AccountManager.getInstance();
    		List<Account> accountList;
    		if(nickname.isEmpty()) {
    			// Se nessun parametro viene utilizzato restituiamo tutta la lista
    			accountList = manager.getAccountList();
    		} else {
    			Account toSearch = new Account();
    			toSearch.setNickname(nickname);
    			accountList = manager.search(toSearch);
    		}
    		
    		// Inoltro della risposta
    		request.setAttribute("accountList", accountList);
    		request.getServletContext().getRequestDispatcher("/account/search.jsp").forward(request, response);
    	} catch(InvalidParameterException | NullPointerException e) {
			request.setAttribute("error", e.getMessage());
    		request.getRequestDispatcher("/errorPage.jsp").forward(request, response);
		}
    }
}
